//
//  MCNewGoodsAddImagesView.swift
//  StoreManage
//
//  Created by MC on 2018/2/6.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCNewGoodsAddImagesView: UIView {

    var isNeedEditImage = false
    var superViewController : UIViewController?
    
    var bigImageCount = 6
    
    var dataArrayM : NSMutableArray = NSMutableArray() {
        didSet {
            self.colleciontView.reloadData()
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.white
        
        self.addSubview(promptLabel)
        promptLabel.snp.remakeConstraints { (make) ->Void in
            make.top.equalTo(self)
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.height.equalTo(30)
        }
        
        self.addSubview(colleciontView)
        colleciontView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(promptLabel.snp.bottom).offset(0)
            make.bottom.equalTo(self).offset(0)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    lazy var promptLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(14)
        label.text = "商品海报图"
        label.textColor = UIColor.MCBlack
        return label
    }()
    
    
    @objc func deleteEvent(sender:UIButton) {
        let tag = sender.tag - 1000
        dataArrayM.removeObject(at: tag)
        colleciontView.reloadData()
    }
    
    func chooseImage() {
        
        let alterController = UIAlertController.init(title: "选择图片", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet);
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
        })
        let libraryAction = UIAlertAction.init(title: "图库", style: UIAlertActionStyle.default, handler: { (action) in
            self.libraryClicked()
        })
        
        let cameraAction = UIAlertAction.init(title: "拍照", style: UIAlertActionStyle.default, handler: { (action) in
            self.cameraClicked()
        })
        
        alterController.addAction(cancelAction)
        alterController.addAction(libraryAction)
        alterController.addAction(cameraAction)
        
        superViewController?.present(alterController, animated: true, completion: {})
    }
    
    
    // 图库
    func libraryClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = isNeedEditImage
            vc.sourceType = UIImagePickerControllerSourceType.photoLibrary
            superViewController?.present(vc, animated: true, completion: { })
        }
    }
    
    func cameraClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            
            let availableMeidatypes : NSArray = UIImagePickerController.availableMediaTypes(for: UIImagePickerControllerSourceType.camera)! as NSArray
            
            var canTakePicture = false
            
            for mediaType in availableMeidatypes {
                
                let str = mediaType as? String
                
                if str == String(kUTTypeImage) {
                    canTakePicture = true
                    break
                }
            }
            
            guard canTakePicture else {
                return
            }
            
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = isNeedEditImage
            vc.sourceType = UIImagePickerControllerSourceType.camera
            vc.mediaTypes = NSArray(object: String(kUTTypeImage)) as! [String]
            superViewController?.present(vc, animated: true, completion: { })
            
        }
    }


    

    private lazy var colleciontView: UICollectionView = {
        
        //  68  97
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal
        
        let margin = 10
        let itemWidth : CGFloat = 90
        let itemHeight : CGFloat = 90
        
        layout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0)
        
        layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight)
        layout.minimumLineSpacing = CGFloat(margin)
        layout.minimumInteritemSpacing = CGFloat(margin)
        
        let collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        collectionView.register(MCNewGoodsAddImagesCell.classForCoder(), forCellWithReuseIdentifier: "imageCell")

        return collectionView
    }()    
}

extension MCNewGoodsAddImagesView : UICollectionViewDelegate,UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if dataArrayM.count >= bigImageCount {
            return dataArrayM.count
        } else {
            return dataArrayM.count + 1
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if dataArrayM.count >= bigImageCount {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! MCNewGoodsAddImagesCell
            
            for view in cell.contentView.subviews {
                view.removeFromSuperview()
            }
            cell.bgImageView.image = self.dataArrayM[indexPath.row] as? UIImage
            cell.row = indexPath.row
            cell.delegate = self
            return cell
        }
        
        
        if indexPath.row == dataArrayM.count {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
            
            for view in cell.contentView.subviews {
                view.removeFromSuperview()
            }
            
            let imageView = UIImageView()
            imageView.image = #imageLiteral(resourceName: "GoodsManage_add_square")
            imageView.layer.borderColor = UIColor.MCGray_light.cgColor
            imageView.layer.borderWidth = 1
            cell.contentView.addSubview(imageView)
            imageView.snp.remakeConstraints { (make) ->Void in
                make.edges.equalTo(cell.contentView)
            }
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! MCNewGoodsAddImagesCell
            
            for view in cell.contentView.subviews {
                view.removeFromSuperview()
            }
            cell.bgImageView.image = self.dataArrayM[indexPath.row] as? UIImage
            cell.row = indexPath.row
            cell.delegate = self
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if dataArrayM.count == 0 {
            self.chooseImage()
        } else {
            
            if dataArrayM.count >= bigImageCount {
                print("点击了图片")
            } else {
                if indexPath.row == dataArrayM.count {
                    self.chooseImage()
                } else {
                    print("点击了图片")
                }
            }
            
        }
    }
}

extension MCNewGoodsAddImagesView : MCNewGoodsAddImagesCellDelegate {
    func MCNewGoodsAddImagesCellCancel(row: Int) {
        self.dataArrayM.removeObject(at: row)
        self.colleciontView.reloadData()
    }
}

extension MCNewGoodsAddImagesView: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let mediaType = info[UIImagePickerControllerMediaType] as! String
        
        if mediaType == String(kUTTypeImage) {
            
            if isNeedEditImage {
                let originalImage : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
                
                let rect = info[UIImagePickerControllerCropRect] as! CGRect
                
                let editedImage = originalImage.MCImageCrop(toRect: rect)
                self.dataArrayM.add(editedImage)
            } else {
                let originalImage : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
                self.dataArrayM.add(originalImage)
            }
            
            
            self.colleciontView.reloadData()
            
            var item = (self.dataArrayM.count)
            if self.dataArrayM.count >= bigImageCount {
                 item -= 1
            }
            let lastItemIndex = IndexPath.init(row: item, section: 0)
            self.colleciontView.scrollToItem(at: lastItemIndex, at: UICollectionViewScrollPosition.right, animated: true)
            picker.dismiss(animated: true, completion: nil)

        }
    }
}


